/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package coalescent.phylogeny;

import commons.util.BinaryDataUtil;
import commons.util.ExceptionUtil;
import commons.util.IterableUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This enum defines an interface for checking phylogeny of {@code K69Data}. Enum constants provide
 * supported algorithm implementations.
 * <p>
 * Note that checking phylogeny is equivalent to checking the infinite sites assumption, a feature
 * of the {@code K69} model. {@code K69Data} is supposed to follow the {@code K69} model and a
 * phylogeny test can be used to check if the data deviates from the model.
 *
 * @author Susanta Tewari
 * @version 2.0.0
 * @history Created on 11/24/2010 (PhylogenyAlgorithm)
 * @since 1.3.0
 */
public enum CheckPPhylogenyAlgo {

    /**
     * {@code CheckPPhylogenyAlgo} algorithm from Dan Gusfield. The reference:
     * "Efficient Algorithms for Inferring  Evolutionary Trees", By Dan Gusfield, Networks Vol. 21 (1991) 19-28.
     */
    GUSFIELD {

        /**
         * Method description
         *
         *
         * @param data
         *
         * @return
         */
        @Override
        public boolean isPhylogeny(final Iterable<byte[]> data) {

            checkData(data);

            GusfieldAlgorithm algo = new GusfieldAlgorithm(data, "0", "-");

            return algo.isPhylogeny();
        }
    },

    /**
     * {@code CheckPPhylogenyAlgo} algorithm from Richard R. Hudson. The reference:
     * "Statistical Properties of the number of recombination events in the history of a sample
     * of DNA sequences", By Hudson et. al., Genetics Vol. 111 (1985) 147-164.
     */
    FOURGAMETES {

        /**
         * Method description
         *
         *
         * @param data
         *
         * @return
         */
        @Override
        public boolean isPhylogeny(final Iterable<byte[]> data) {

            checkData(data);

            FourGametesAlgorithm algo = new FourGametesAlgorithm();

            return algo.isPhylogeny(data);
        }
    };

    /**
     * Checks the phylogeny of the specified data.
     *
     * @param data data whose phylogeny is tested
     * @return {@code true} if {@code data} has phylogeny; {@code false} otherwise
     */
    public abstract boolean isPhylogeny(final Iterable<byte[]> data);

    /**
     * A convenient method that delegates to {@link #isPhylogeny(java.lang.Iterable)}.
     *
     * @param data data whose phylogeny is tested (the strings should contain only 0 and/or 1)
     * @return {@code true} if {@code data} has phylogeny; {@code false} otherwise
     */
    public final boolean isPhylogeny2(final Collection<String> data) {
        return isPhylogeny(BinaryDataUtil.transformData(data));
    }

    /**
     * Checks if the parameter {@code data} contains values other than 0 or 1
     *
     * @param data containing values 0 or 1
     * @throws NullPointerException if parameter {@code data} is {@code null}
     * @throws IllegalArgumentException if, *) all arrays in {@code data} are not of same length *)
     * the byte arrays contain values other than 0 or 1
     */
    static void checkData(final Iterable<byte[]> data) {


        // check data is square
        byte[] firstdata = data.iterator().next();

        for (byte[] val : data) {

            if (firstdata.length != val.length) {

                ExceptionUtil.throwIllegalArgEx(CheckPPhylogenyAlgo.class,
                                                "Allele_Length_Mismatch", Arrays.toString(val));
            }

            for (int i = 0; i < val.length; i++) {

                if (!((val[i] == 0) || (val[i] == 1))) {

                    ExceptionUtil.throwIllegalArgEx(CheckPPhylogenyAlgo.class, "Allele_Not_Binary",
                                                    "" + (i + 1));
                }
            }
        }
    }


    // <editor-fold defaultstate="collapsed" desc="FourGametesAlgorithm">

    /**
     * An implementation of {@code CheckPPhylogenyAlgo} from the following reference.
     * "Statistical Properties of the number of recombination events in the history of a sample
     * of DNA sequences", By Hudson et. al., Genetics Vol. 111 (1985) 147-164.
     *
     * @author Susanta Tewari
     * @version 1.0 Nov 24, 2010
     */
    private static class FourGametesAlgorithm {

        /**
         * Method description
         *
         *
         * @param alleles
         *
         * @return
         */
        public boolean isPhylogeny(final Iterable<byte[]> alleles) {


            // create alleles (used for reporting errors)
            List<String> allele_list = new ArrayList<>(10);

            for (byte[] val : alleles) {

                allele_list.add(BinaryDataUtil.buildBinaryString(val));
            }


            // iterable to array
            byte[][] data = IterableUtil.toArray(alleles);


            // the algo
            for (int i = 0; i < data[0].length - 1; i++) {

                for (int j = i + 1; j < data[0].length; j++) {


                    // for sites i and j, scan for all four gamete patterns
                    boolean gamete1 = false,
                            gamete2 = false,
                            gamete3 = false,
                            gamete4 = false;


                    // alleles that witnessed the gametes first
                    int k1 = 0,
                        k2 = 0,
                        k3 = 0,
                        k4 = 0;

                    for (int k = 0; k < data.length; k++) {

                        if ((data[k][i] == 0) && (data[k][j] == 0) &&!gamete1) {

                            k1      = k;
                            gamete1 = true;

                        } else if ((data[k][i] == 0) && (data[k][j] == 1) &&!gamete2) {

                            k2      = k;
                            gamete2 = true;

                        } else if ((data[k][i] == 1) && (data[k][j] == 0) &&!gamete3) {

                            k3      = k;
                            gamete3 = true;

                        } else if ((data[k][i] == 1) && (data[k][j] == 1) &&!gamete4) {

                            k4      = k;
                            gamete4 = true;
                        }

                        if (gamete1 && gamete2 && gamete3 && gamete4) {

                            String message = "Alleles " + allele_list.get(k1) + ", "
                                             + allele_list.get(k2) + ", " + allele_list.get(k3)
                                             + ", " + allele_list.get(k4)
                                             + " have four gametes for sites : " + (i + 1)
                                             + " and " + (j + 1) + "\n";

                            Logger.getLogger(this.getClass().getName()).log(Level.INFO, message);

                            return false;
                        }
                    }
                }
            }

            return true;
        }
    }    // </editor-fold>
}
